// LoginPage.tsx
import { useState, FormEvent, ChangeEvent, useEffect } from "react";
import { ArrowRight, Mail, Lock, AlertCircle } from "lucide-react";
import {
    Form,
    Link,
    useActionData,
    useNavigate,
    useSubmit,
} from "@remix-run/react";
import { login } from "~/models/mock";
import { ActionFunctionArgs } from "@remix-run/cloudflare";
import { User } from "~/models";
import { Input } from "~/components/ui/input";
import { Button } from "~/components/ui/button";

// types.ts
export interface FormData {
    email: string;
    password: string;
}

export interface FormErrors {
    email?: string;
    password?: string;
    submit?: string;
}

type ActionData = {
    user?: User;
    error?: string;
};

export const action = async ({ request }: ActionFunctionArgs) => {
    const formData = await request.formData();
    console.log(formData);
    const email = (formData.get("email") as string) || "";
    const password = (formData.get("password") as string) || "";

    if (!email || !password) {
        return Response.json({ error: "请输入邮箱和密码" }, { status: 400 });
    }

    const user = login(email, password);
    if (!user) {
        return Response.json({ error: "邮箱或密码错误" }, { status: 400 });
    }
    return Response.json({ user });
};

const LoginPage: React.FC = () => {
    const actionData = useActionData<ActionData>();
    const navigate = useNavigate();
    const submit = useSubmit();

    useEffect(() => {
        setIsLoading(false);
        const userLogged = localStorage.getItem("userLogged");
        if (userLogged) {
            location.pathname = "/features/t2i";
        }

        if (actionData?.user) {
            localStorage.setItem("userLogged", JSON.stringify(actionData.user));
            navigate("/features/t2i");
        }

        if (actionData?.error) {
            setErrors({
                submit: actionData.error,
            });
        }
    }, [actionData, navigate]);

    const [formData, setFormData] = useState<FormData>({
        email: "",
        password: "",
    });

    const [errors, setErrors] = useState<FormErrors>({});
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [showPassword, setShowPassword] = useState<boolean>(false);

    const validate = (): FormErrors => {
        const newErrors: FormErrors = {};

        // Email validation
        if (!formData.email) {
            newErrors.email = "请输入邮箱";
        } else if (
            !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(formData.email)
        ) {
            newErrors.email = "请输入有效的邮箱地址";
        }

        // Password validation
        if (!formData.password) {
            newErrors.password = "请输入密码";
        } else if (formData.password.length < 6) {
            newErrors.password = "密码长度至少6位";
        }

        return newErrors;
    };

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>): void => {
        const { name, value } = e.target;
        setFormData((prev: FormData) => ({
            ...prev,
            [name]: value,
        }));

        // Clear error when user starts typing
        if (errors[name as keyof FormErrors]) {
            setErrors((prev: FormErrors) => ({
                ...prev,
                [name]: "",
            }));
        }
    };

    const handleSubmit = async (
        e: FormEvent<HTMLFormElement>
    ): Promise<void> => {
        const formData = new FormData(e.currentTarget);
        const newErrors = validate();

        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
            return;
        }

        setIsLoading(true);

        submit(formData);
    };

    // Logo component
    const Logo: React.FC = () => (
        <svg viewBox="0 0 200 50" className="h-12 mx-auto">
            <defs>
                <linearGradient
                    id="logoGradient"
                    x1="0%"
                    y1="0%"
                    x2="100%"
                    y2="0%"
                >
                    <stop
                        offset="0%"
                        style={{ stopColor: "#34D399", stopOpacity: 1 }}
                    />
                    <stop
                        offset="100%"
                        style={{ stopColor: "#059669", stopOpacity: 1 }}
                    />
                </linearGradient>
            </defs>
            <path d="M40 35L25 20L10 35V45H40V35Z" fill="url(#logoGradient)" />
            <path
                d="M25 15L5 35H45L25 15Z"
                fill="url(#logoGradient)"
                opacity="0.7"
            />
            <circle cx="20" cy="30" r="2" fill="#059669" />
            <circle cx="30" cy="30" r="2" fill="#059669" />
            <circle cx="25" cy="25" r="2" fill="#059669" />
            <line
                x1="20"
                y1="30"
                x2="25"
                y2="25"
                stroke="#059669"
                strokeWidth="1"
            />
            <line
                x1="30"
                y1="30"
                x2="25"
                y2="25"
                stroke="#059669"
                strokeWidth="1"
            />
            <text
                x="55"
                y="40"
                fill="#059669"
                fontFamily="Arial"
                fontSize="24"
                fontWeight="bold"
            >
                宅绘云坊
            </text>
        </svg>
    );

    return (
        <div className="min-h-screen bg-gradient-to-br from-emerald-50 to-green-50 flex items-center justify-center p-4">
            <div className="w-full max-w-md">
                {/* Logo */}
                <div className="text-center mb-8 transform transition-all duration-500 hover:scale-105">
                    <Logo />
                </div>

                {/* Login Form */}
                <div className="bg-white rounded-2xl shadow-xl p-8 transform transition-all duration-500 hover:shadow-2xl">
                    <h2 className="text-2xl font-bold text-center text-gray-800 mb-8">
                        欢迎登录
                    </h2>

                    <Form
                        id="login-form"
                        method="post"
                        onSubmit={handleSubmit}
                        className="space-y-6"
                    >
                        {/* Email Input */}
                        <div className="space-y-2">
                            <label
                                htmlFor="email"
                                className="text-sm font-medium text-gray-700 block"
                            >
                                邮箱
                            </label>
                            <div className="relative">
                                <Input
                                    id="email"
                                    name="email"
                                    type="email"
                                    autoComplete="email"
                                    required
                                    className={`w-full px-4 py-3 rounded-lg border ${
                                        errors.email
                                            ? "border-red-500"
                                            : "border-gray-200"
                                    } focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent pl-10 transition-all duration-300`}
                                    placeholder="请输入邮箱地址"
                                    value={formData.email}
                                    onChange={handleInputChange}
                                    aria-invalid={Boolean(errors.email)}
                                    aria-describedby={
                                        errors.email ? "email-error" : undefined
                                    }
                                />
                                <Mail className="w-5 h-5 text-gray-400 absolute left-3 top-2" />
                            </div>
                            {errors.email && (
                                <p
                                    id="email-error"
                                    className="text-red-500 text-sm flex items-center gap-1"
                                >
                                    <AlertCircle className="w-4 h-4" />
                                    {errors.email}
                                </p>
                            )}
                        </div>

                        {/* Password Input */}
                        <div className="space-y-2">
                            <label
                                htmlFor="password"
                                className="text-sm font-medium text-gray-700 block"
                            >
                                密码
                            </label>
                            <div className="relative">
                                <Input
                                    id="password"
                                    name="password"
                                    type={showPassword ? "text" : "password"}
                                    autoComplete="current-password"
                                    required
                                    className={`w-full px-4 py-3 rounded-lg border ${
                                        errors.password
                                            ? "border-red-500"
                                            : "border-gray-200"
                                    } focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent pl-10 transition-all duration-300`}
                                    placeholder="请输入密码"
                                    value={formData.password}
                                    onChange={handleInputChange}
                                    aria-invalid={Boolean(errors.password)}
                                    aria-describedby={
                                        errors.password
                                            ? "password-error"
                                            : undefined
                                    }
                                />
                                <Lock className="w-5 h-5 text-gray-400 absolute left-3 top-2" />
                                <button
                                    type="button"
                                    className="absolute right-3 top-2 text-gray-400 hover:text-gray-600"
                                    onClick={() =>
                                        setShowPassword(!showPassword)
                                    }
                                    aria-label={
                                        showPassword ? "隐藏密码" : "显示密码"
                                    }
                                >
                                    {showPassword ? "隐藏" : "显示"}
                                </button>
                            </div>
                            {errors.password && (
                                <p
                                    id="password-error"
                                    className="text-red-500 text-sm flex items-center gap-1"
                                >
                                    <AlertCircle className="w-4 h-4" />
                                    {errors.password}
                                </p>
                            )}
                        </div>

                        {/* Additional Options */}
                        <div className="flex items-center justify-between text-sm">
                            <label className="flex items-center">
                                <input
                                    type="checkbox"
                                    className="rounded bg-white border-gray-300 text-emerald-600 focus:ring-emerald-500"
                                />
                                <span className="ml-2 text-gray-600">
                                    记住我
                                </span>
                            </label>
                            <Link
                                to="/forget-password"
                                className="text-emerald-600 hover:text-emerald-500"
                                onClick={(e) => e.preventDefault()}
                            >
                                忘记密码？
                            </Link>
                        </div>

                        {/* Submit Button */}
                        <Button
                            type="submit"
                            disabled={isLoading}
                            className="w-full bg-emerald-600 text-white py-3 px-4 rounded-lg hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 transition-all duration-300 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {isLoading ? (
                                <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
                            ) : (
                                <>
                                    登录
                                    <ArrowRight className="w-5 h-5" />
                                </>
                            )}
                        </Button>

                        {/* Error Message */}
                        {errors.submit && (
                            <p
                                role="alert"
                                className="text-red-500 text-sm text-center flex items-center justify-center gap-1"
                            >
                                <AlertCircle className="w-4 h-4" />
                                {errors.submit}
                            </p>
                        )}
                    </Form>

                    {/* Register Link */}
                    <p className="text-center mt-6 text-gray-600">
                        还没有账号？
                        <Link
                            to="/register"
                            className="text-emerald-600 hover:text-emerald-500 ml-1"
                            onClick={(e) => e.preventDefault()}
                        >
                            立即注册
                        </Link>
                    </p>
                </div>
            </div>
        </div>
    );
};

export default LoginPage;
